package com.citic.topview.system.filter;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.citic.topview.system.util.StringUtils;

public class XSSRequestWrapper extends HttpServletRequestWrapper {
	
	HttpServletRequest orgRequest = null;  
	  
    public XSSRequestWrapper(HttpServletRequest request) {  
        super(request);  
        orgRequest = request;  
    }  
  
    public HttpServletRequest getOrgRequest() {  
        return orgRequest;  
    }  
  
    public static HttpServletRequest getOrgRequest(HttpServletRequest req) {  
        if (req instanceof XSSRequestWrapper) {  
            return ((XSSRequestWrapper) req).getOrgRequest();  
        }  
  
        return req;  
    }  
    
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);  
        
        if (value != null) {  
            value = StringUtils.xssEncode(value);  
            value = StringUtils.HTMLEncode(value);  
        }  
        return value;  
    }
    
    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values == null){
        	return null;
        }
        
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
        	if(values[i] != null){
        		encodedValues[i] = StringUtils.xssEncode(values[i]);  
        		encodedValues[i] = StringUtils.HTMLEncode(encodedValues[i]);  
        	}
        }
        
        return encodedValues;
    }
    
    @Override
    public Map<String, String[]> getParameterMap() {
		Map<String, String[]> request_map = super.getParameterMap();  
        Iterator<Map.Entry<String, String[]>> iterator = request_map.entrySet().iterator();  
        while (iterator.hasNext()) {  
            Map.Entry<String, String[]> me = (Map.Entry<String, String[]>) iterator.next();  
            String[] values = (String[]) me.getValue();  
            for (int i = 0; i < values.length; i++) {  
                values[i] = StringUtils.xssEncode(values[i]);  
                values[i] = StringUtils.HTMLEncode(values[i]);  
            }  
        }  
        return request_map;  
    }
    
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null)
            return null;
        return StringUtils.xssEncode(value);
    }
    
}
